<!doctype html><html lang="zh"><head><meta charset="utf-8"><meta name="generator" content="Hexo 4.2.1"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1"><meta><title>JAVA与模式之责任链模式 - Trainoo的博客</title><meta description="开发者,程序猿,编程,代码,开源,IT网站,Developer,Programmer,Coder"><meta property="og:type" content="blog"><meta property="og:title" content="Trainoo"><meta property="og:url" content="/"><meta property="og:site_name" content="Trainoo"><meta property="og:description" content="开发者,程序猿,编程,代码,开源,IT网站,Developer,Programmer,Coder"><meta property="og:locale" content="zh_CN"><meta property="og:image" content="/img/header.png"><meta property="article:published_time" content="2017-12-23T16:00:00.000Z"><meta property="article:modified_time" content="2021-04-12T09:28:12.148Z"><meta property="article:author" content="Trainoo"><meta property="article:tag" content="java"><meta property="article:tag" content="设计模式"><meta property="article:tag" content="转载"><meta property="twitter:card" content="summary"><meta property="twitter:image" content="/img/header.png"><script type="application/ld+json">{"@context":"https://schema.org","@type":"BlogPosting","mainEntityOfPage":{"@type":"WebPage","@id":"/"},"headline":"Trainoo","image":["/img/header.png"],"datePublished":"2017-12-23T16:00:00.000Z","dateModified":"2021-04-12T09:28:12.148Z","author":{"@type":"Person","name":"Trainoo"},"description":"开发者,程序猿,编程,代码,开源,IT网站,Developer,Programmer,Coder"}</script><link rel="canonical" href="https://trainoo.gitee.io/2017/12/24/Java-design-pattern-responsibility-chain/"><link rel="alternative" href="/atom.xml" title="Trainoo的博客" type="application/atom+xml"><link rel="icon" href="/img/favicon.png"><link rel="stylesheet" href="/cdn/css/fontawesome.all.css"><link rel="stylesheet" href="/cdn/js/styles/atom-one-light.css"><link rel="stylesheet" href="/cdn/css/css2.css"><link rel="stylesheet" href="/css/default.css"><style>body>.footer,body>.navbar,body>.section{opacity:0}</style><script src="/cdn/js/pace.min.js"></script><script src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" defer></script><link rel="stylesheet" href="/cdn/js/dist/css/lightgallery.min.css"><link rel="stylesheet" href="/cdn/js/dist/css/justifiedGallery.min.css"></head><body class="is-2-column"><script type="text/javascript" src="/js/theme-night.js"></script><canvas id="universe"></canvas><nav class="navbar navbar-main"><div class="container"><div class="navbar-brand justify-content-center"><a class="navbar-item navbar-logo" href="/"><img class="navbar-logo-img" src="/img/logo.png" alt="Trainoo的博客" height="28"></a></div><div class="navbar-menu"><div class="navbar-start"><a class="navbar-item" href="/">首页</a><a class="navbar-item" href="/archives">时间轴</a><a class="navbar-item" href="/categories/%E7%9B%B8%E5%86%8C">相册</a><a class="navbar-item" href="/friend">友链</a><a class="navbar-item" href="/about">关于</a></div><div class="navbar-end"><a class="navbar-item" target="_blank" rel="noopener" title="Download on GitHub" href="https://github.com/trainoozhou"><i class="fab fa-github"></i></a><a class="navbar-item search" title="搜索" href="javascript:;"><i class="fas fa-search"></i></a><a class="navbar-item" id="night-nav" title="Night Mode" href="javascript:;"><i class="fas fa-moon" id="night-icon"></i></a></div></div></div></nav><section class="section"><div class="container"><div class="columns"><div class="column order-2 column-main is-8-tablet is-8-desktop is-8-widescreen"><div class="card"><div class="card-image"><span class="image is-7by3"><img class="thumbnail" src="/picture/2018/20180624001.png" alt="JAVA与模式之责任链模式"></span></div><article class="card-content article" role="article"><div class="article-meta size-small is-uppercase level is-mobile"><div class="level-left"><time class="level-item" datetime="2017-12-23T16:00:00.000Z" title="2017-12-23T16:00:00.000Z">2017-12-24</time><span class="level-item"><a class="link-muted" href="/categories/%E5%AD%A6%E4%B9%A0/">学习</a><span> / </span><a class="link-muted" href="/categories/%E5%AD%A6%E4%B9%A0/java/">java</a></span><span class="level-item" id="busuanzi_container_page_pv"><i class="far fa-eye"></i>&nbsp;&nbsp;<span id="busuanzi_value_page_pv">0</span>次访问</span></div></div><h1 class="title is-3 is-size-4-mobile">JAVA与模式之责任链模式</h1><div class="content"><blockquote><p>转载自java_my_life的博客<br>作者： java_my_life<br>原文地址：<a href="http://www.cnblogs.com/java-my-life/archive/2012/05/28/2516865.html">http://www.cnblogs.com/java-my-life/archive/2012/05/28/2516865.html</a></p></blockquote><a id="more"></a><p>在阎宏博士的《JAVA与模式》一书中开头是这样描述责任链（Chain of Responsibility）模式的：</p><p><strong>责任链模式是一种对象的行为模式。在责任链模式里，很多对象由每一个对象对其下家的引用而连接起来形成一条链。请求在这个链上传递，直到链上的某一个对象决定处理此请求。发出这个请求的客户端并不知道链上的哪一个对象最终处理这个请求，这使得系统可以在不影响客户端的情况下动态地重新组织和分配责任。</strong></p><h2 id="从击鼓传花谈起"><a href="#从击鼓传花谈起" class="headerlink" title="从击鼓传花谈起."></a>从击鼓传花谈起.</h2><p>击鼓传花是一种热闹而又紧张的饮酒游戏。在酒宴上宾客依次坐定位置，由一人击鼓，击鼓的地方与传花的地方是分开的，以示公正。开始击鼓时，花束就开始依次传递，鼓声一落，如果花束在某人手中，则该人就得饮酒。</p><p>比如说，贾母、贾赦、贾政、贾宝玉和贾环是五个参加击鼓传花游戏的传花者，他们组成一个环链。击鼓者将花传给贾母，开始传花游戏。花由贾母传给贾赦，由贾赦传给贾政，由贾政传给贾宝玉，又贾宝玉传给贾环，由贾环传回给贾母，如此往复，如下图所示。当鼓声停止时，手中有花的人就得执行酒令。</p><img style="display:block;margin-left:auto;margin-right:auto" src="" alt=""> 击鼓传花便是责任链模式的应用。责任链可能是一条直线、一个环链或者一个树结构的一部分。<h2 id="责任链模式的结构"><a href="#责任链模式的结构" class="headerlink" title="责任链模式的结构"></a>责任链模式的结构</h2><p>下面使用了一个责任链模式的最简单的实现。<br><img style="display:block;margin-left:auto;margin-right:auto" src="" alt=""></p><p>责任链模式涉及到的角色如下所示：</p><p><strong>- 抽象处理者(Handler)角色：</strong> 定义出一个处理请求的接口。如果需要，接口可以定义 出一个方法以设定和返回对下家的引用。这个角色通常由一个Java抽象类或者Java接口实现。上图中Handler类的聚合关系给出了具体子类对下家的引用，抽象方法handleRequest()规范了子类处理请求的操作。</p><p><strong>- 具体处理者(ConcreteHandler)角色：</strong> 具体处理者接到请求后，可以选择将请求处理掉，或者将请求传给下家。由于具体处理者持有对下家的引用，因此，如果需要，具体处理者可以访问下家。</p><h3 id="源代码"><a href="#源代码" class="headerlink" title="源代码"></a>源代码</h3><p>抽象处理者角色</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">public abstract class Handler &#123;</span><br><span class="line">    </span><br><span class="line">    &#x2F;**</span><br><span class="line">     * 持有后继的责任对象</span><br><span class="line">     *&#x2F;</span><br><span class="line">    protected Handler successor;</span><br><span class="line">    &#x2F;**</span><br><span class="line">     * 示意处理请求的方法，虽然这个示意方法是没有传入参数的</span><br><span class="line">     * 但实际是可以传入参数的，根据具体需要来选择是否传递参数</span><br><span class="line">     *&#x2F;</span><br><span class="line">    public abstract void handleRequest();</span><br><span class="line">    &#x2F;**</span><br><span class="line">     * 取值方法</span><br><span class="line">     *&#x2F;</span><br><span class="line">    public Handler getSuccessor() &#123;</span><br><span class="line">        return successor;</span><br><span class="line">    &#125;</span><br><span class="line">    &#x2F;**</span><br><span class="line">     * 赋值方法，设置后继的责任对象</span><br><span class="line">     *&#x2F;</span><br><span class="line">    public void setSuccessor(Handler successor) &#123;</span><br><span class="line">        this.successor &#x3D; successor;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>具体处理者角色</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">public class ConcreteHandler extends Handler &#123;</span><br><span class="line">    &#x2F;**</span><br><span class="line">     * 处理方法，调用此方法处理请求</span><br><span class="line">     *&#x2F;</span><br><span class="line">    @Override</span><br><span class="line">    public void handleRequest() &#123;</span><br><span class="line">        &#x2F;**</span><br><span class="line">         * 判断是否有后继的责任对象</span><br><span class="line">         * 如果有，就转发请求给后继的责任对象</span><br><span class="line">         * 如果没有，则处理请求</span><br><span class="line">         *&#x2F;</span><br><span class="line">        if(getSuccessor() !&#x3D; null)</span><br><span class="line">        &#123;            </span><br><span class="line">            System.out.println(&quot;放过请求&quot;);</span><br><span class="line">            getSuccessor().handleRequest();            </span><br><span class="line">        &#125;else</span><br><span class="line">        &#123;            </span><br><span class="line">            System.out.println(&quot;处理请求&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>客户端类</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">public class Client &#123;</span><br><span class="line"></span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        &#x2F;&#x2F;组装责任链</span><br><span class="line">        Handler handler1 &#x3D; new ConcreteHandler();</span><br><span class="line">        Handler handler2 &#x3D; new ConcreteHandler();</span><br><span class="line">        handler1.setSuccessor(handler2);</span><br><span class="line">        &#x2F;&#x2F;提交请求</span><br><span class="line">        handler1.handleRequest();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>可以看出，客户端创建了两个处理者对象，并指定第一个处理者对象的下家是第二个处理者对象，而第二个处理者对象没有下家。然后客户端将请求传递给第一个处理者对象。</p><p>由于本示例的传递逻辑非常简单：只要有下家，就传给下家处理；如果没有下家，就自行处理。因此，第一个处理者对象接到请求后，会将请求传递给第二个处理者对象。由于第二个处理者对象没有下家，于是自行处理请求。活动时序图如下所示。<br><img style="display:block;margin-left:auto;margin-right:auto" src="" alt=""></p><h2 id="使用场景"><a href="#使用场景" class="headerlink" title="使用场景"></a>使用场景</h2><p>来考虑这样一个功能:申请聚餐费用的管理。</p><p>　　很多公司都是这样的福利，就是项目组或者是部门可以向公司申请一些聚餐费用，用于组织项目组成员或者是部门成员进行聚餐活动。</p><p>　　申请聚餐费用的大致流程一般是：由申请人先填写申请单，然后交给领导审批，如果申请批准下来，领导会通知申请人审批通过，然后申请人去财务领取费用，如果没有批准下来，领导会通知申请人审批未通过，此事也就此作罢。</p><p>　　不同级别的领导，对于审批的额度是不一样的，比如，项目经理只能审批500元以内的申请；部门经理能审批1000元以内的申请；而总经理可以审核任意额度的申请。</p><p>　　也就是说，当某人提出聚餐费用申请的请求后，该请求会经由项目经理、部门经理、总经理之中的某一位领导来进行相应的处理，但是提出申请的人并不知道最终会由谁来处理他的请求，一般申请人是把自己的申请提交给项目经理，或许最后是由总经理来处理他的请求。</p><p>　　可以使用责任链模式来实现上述功能：当某人提出聚餐费用申请的请求后，该请求会在 项目经理—〉部门经理—〉总经理 这样一条领导处理链上进行传递，发出请求的人并不知道谁会来处理他的请求，每个领导会根据自己的职责范围，来判断是处理请求还是把请求交给更高级别的领导，只要有领导处理了，传递就结束了。</p><p>　　需要把每位领导的处理独立出来，实现成单独的职责处理对象，然后为它们提供一个公共的、抽象的父职责对象，这样就可以在客户端来动态地组合职责链，实现不同的功能要求了。</p><img style="display:block;margin-left:auto;margin-right:auto" src="" alt=""><h3 id="源代码-1"><a href="#源代码-1" class="headerlink" title="源代码"></a>源代码</h3><p>抽象处理者角色类</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">public abstract class Handler &#123;</span><br><span class="line">    &#x2F;**</span><br><span class="line">     * 持有下一个处理请求的对象</span><br><span class="line">     *&#x2F;</span><br><span class="line">    protected Handler successor &#x3D; null;</span><br><span class="line">    &#x2F;**</span><br><span class="line">     * 取值方法</span><br><span class="line">     *&#x2F;</span><br><span class="line">    public Handler getSuccessor() &#123;</span><br><span class="line">        return successor;</span><br><span class="line">    &#125;</span><br><span class="line">    &#x2F;**</span><br><span class="line">     * 设置下一个处理请求的对象</span><br><span class="line">     *&#x2F;</span><br><span class="line">    public void setSuccessor(Handler successor) &#123;</span><br><span class="line">        this.successor &#x3D; successor;</span><br><span class="line">    &#125;</span><br><span class="line">    &#x2F;**</span><br><span class="line">     * 处理聚餐费用的申请</span><br><span class="line">     * @param user    申请人</span><br><span class="line">     * @param fee    申请的钱数</span><br><span class="line">     * @return        成功或失败的具体通知</span><br><span class="line">     *&#x2F;</span><br><span class="line">    public abstract String handleFeeRequest(String user , double fee);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>具体处理者角色</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">public class ProjectManager extends Handler &#123;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public String handleFeeRequest(String user, double fee) &#123;</span><br><span class="line">        </span><br><span class="line">        String str &#x3D; &quot;&quot;;</span><br><span class="line">        &#x2F;&#x2F;项目经理权限比较小，只能在500以内</span><br><span class="line">        if(fee &lt; 500)</span><br><span class="line">        &#123;</span><br><span class="line">            &#x2F;&#x2F;为了测试，简单点，只同意张三的请求</span><br><span class="line">            if(&quot;张三&quot;.equals(user))</span><br><span class="line">            &#123;</span><br><span class="line">                str &#x3D; &quot;成功：项目经理同意【&quot; + user + &quot;】的聚餐费用，金额为&quot; + fee + &quot;元&quot;;    </span><br><span class="line">            &#125;else</span><br><span class="line">            &#123;</span><br><span class="line">                &#x2F;&#x2F;其他人一律不同意</span><br><span class="line">                str &#x3D; &quot;失败：项目经理不同意【&quot; + user + &quot;】的聚餐费用，金额为&quot; + fee + &quot;元&quot;;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;else</span><br><span class="line">        &#123;</span><br><span class="line">            &#x2F;&#x2F;超过500，继续传递给级别更高的人处理</span><br><span class="line">            if(getSuccessor() !&#x3D; null)</span><br><span class="line">            &#123;</span><br><span class="line">                return getSuccessor().handleFeeRequest(user, fee);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        return str;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">public class DeptManager extends Handler &#123;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public String handleFeeRequest(String user, double fee) &#123;</span><br><span class="line">        </span><br><span class="line">        String str &#x3D; &quot;&quot;;</span><br><span class="line">        &#x2F;&#x2F;部门经理的权限只能在1000以内</span><br><span class="line">        if(fee &lt; 1000)</span><br><span class="line">        &#123;</span><br><span class="line">            &#x2F;&#x2F;为了测试，简单点，只同意张三的请求</span><br><span class="line">            if(&quot;张三&quot;.equals(user))</span><br><span class="line">            &#123;</span><br><span class="line">                str &#x3D; &quot;成功：部门经理同意【&quot; + user + &quot;】的聚餐费用，金额为&quot; + fee + &quot;元&quot;;    </span><br><span class="line">            &#125;else</span><br><span class="line">            &#123;</span><br><span class="line">                &#x2F;&#x2F;其他人一律不同意</span><br><span class="line">                str &#x3D; &quot;失败：部门经理不同意【&quot; + user + &quot;】的聚餐费用，金额为&quot; + fee + &quot;元&quot;;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;else</span><br><span class="line">        &#123;</span><br><span class="line">            &#x2F;&#x2F;超过1000，继续传递给级别更高的人处理</span><br><span class="line">            if(getSuccessor() !&#x3D; null)</span><br><span class="line">            &#123;</span><br><span class="line">                return getSuccessor().handleFeeRequest(user, fee);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        return str;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">public class GeneralManager extends Handler &#123;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public String handleFeeRequest(String user, double fee) &#123;</span><br><span class="line">        </span><br><span class="line">        String str &#x3D; &quot;&quot;;</span><br><span class="line">        &#x2F;&#x2F;总经理的权限很大，只要请求到了这里，他都可以处理</span><br><span class="line">        if(fee &gt;&#x3D; 1000)</span><br><span class="line">        &#123;</span><br><span class="line">            &#x2F;&#x2F;为了测试，简单点，只同意张三的请求</span><br><span class="line">            if(&quot;张三&quot;.equals(user))</span><br><span class="line">            &#123;</span><br><span class="line">                str &#x3D; &quot;成功：总经理同意【&quot; + user + &quot;】的聚餐费用，金额为&quot; + fee + &quot;元&quot;;    </span><br><span class="line">            &#125;else</span><br><span class="line">            &#123;</span><br><span class="line">                &#x2F;&#x2F;其他人一律不同意</span><br><span class="line">                str &#x3D; &quot;失败：总经理不同意【&quot; + user + &quot;】的聚餐费用，金额为&quot; + fee + &quot;元&quot;;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;else</span><br><span class="line">        &#123;</span><br><span class="line">            &#x2F;&#x2F;如果还有后继的处理对象，继续传递</span><br><span class="line">            if(getSuccessor() !&#x3D; null)</span><br><span class="line">            &#123;</span><br><span class="line">                return getSuccessor().handleFeeRequest(user, fee);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        return str;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>客户端类</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">public class Client &#123;</span><br><span class="line"></span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        &#x2F;&#x2F;先要组装责任链</span><br><span class="line">        Handler h1 &#x3D; new GeneralManager();</span><br><span class="line">        Handler h2 &#x3D; new DeptManager();</span><br><span class="line">        Handler h3 &#x3D; new ProjectManager();</span><br><span class="line">        h3.setSuccessor(h2);</span><br><span class="line">        h2.setSuccessor(h1);</span><br><span class="line">        </span><br><span class="line">        &#x2F;&#x2F;开始测试</span><br><span class="line">        String test1 &#x3D; h3.handleFeeRequest(&quot;张三&quot;, 300);</span><br><span class="line">        System.out.println(&quot;test1 &#x3D; &quot; + test1);</span><br><span class="line">        String test2 &#x3D; h3.handleFeeRequest(&quot;李四&quot;, 300);</span><br><span class="line">        System.out.println(&quot;test2 &#x3D; &quot; + test2);</span><br><span class="line">        System.out.println(&quot;---------------------------------------&quot;);</span><br><span class="line">        </span><br><span class="line">        String test3 &#x3D; h3.handleFeeRequest(&quot;张三&quot;, 700);</span><br><span class="line">        System.out.println(&quot;test3 &#x3D; &quot; + test3);</span><br><span class="line">        String test4 &#x3D; h3.handleFeeRequest(&quot;李四&quot;, 700);</span><br><span class="line">        System.out.println(&quot;test4 &#x3D; &quot; + test4);</span><br><span class="line">        System.out.println(&quot;---------------------------------------&quot;);</span><br><span class="line">        </span><br><span class="line">        String test5 &#x3D; h3.handleFeeRequest(&quot;张三&quot;, 1500);</span><br><span class="line">        System.out.println(&quot;test5 &#x3D; &quot; + test5);</span><br><span class="line">        String test6 &#x3D; h3.handleFeeRequest(&quot;李四&quot;, 1500);</span><br><span class="line">        System.out.println(&quot;test6 &#x3D; &quot; + test6);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>运行结果如下所示：<br><img src="" alt=""></p><h2 id="纯的与不纯的责任链模式"><a href="#纯的与不纯的责任链模式" class="headerlink" title="纯的与不纯的责任链模式"></a>纯的与不纯的责任链模式</h2><p>　　一个纯的责任链模式要求一个具体的处理者对象只能在两个行为中选择一个：一是承担责任，而是把责任推给下家。不允许出现某一个具体处理者对象在承担了一部分责任后又 把责任向下传的情况。</p><p>　　在一个纯的责任链模式里面，一个请求必须被某一个处理者对象所接收；在一个不纯的责任链模式里面，一个请求可以最终不被任何接收端对象所接收。</p><p>　　纯的责任链模式的实际例子很难找到，一般看到的例子均是不纯的责任链模式的实现。有些人认为不纯的责任链根本不是责任链模式，这也许是有道理的。但是在实际的系统里，纯的责任链很难找到。如果坚持责任链不纯便不是责任链模式，那么责任链模式便不会有太大意义了。</p><h2 id="责任链模式在Tomcat中的应用"><a href="#责任链模式在Tomcat中的应用" class="headerlink" title="责任链模式在Tomcat中的应用"></a>责任链模式在Tomcat中的应用</h2><p>众所周知Tomcat中的Filter就是使用了责任链模式，创建一个Filter除了要在web.xml文件中做相应配置外，还需要实现javax.servlet.Filter接口。</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">public class TestFilter implements Filter&#123;</span><br><span class="line"></span><br><span class="line">    public void doFilter(ServletRequest request, ServletResponse response,</span><br><span class="line">            FilterChain chain) throws IOException, ServletException &#123;</span><br><span class="line">        </span><br><span class="line">        chain.doFilter(request, response);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void destroy() &#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void init(FilterConfig filterConfig) throws ServletException &#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>使用DEBUG模式所看到的结果如下:<br><img style="display:block;margin-left:auto;margin-right:auto" src="" alt=""></p><p>其实在真正执行到TestFilter类之前，会经过很多Tomcat内部的类。顺带提一下其实Tomcat的容器设置也是责任链模式，注意被红色方框所圈中的类，从Engine到Host再到Context一直到Wrapper都是通过一个链传递请求。被绿色方框所圈中的地方有一个名为ApplicationFilterChain的类，ApplicationFilterChain类所扮演的就是抽象处理者角色，而具体处理者角色由各个Filter扮演。</p><h5 id="第一个疑问是ApplicationFilterChain将所有的Filter存放在哪里？"><a href="#第一个疑问是ApplicationFilterChain将所有的Filter存放在哪里？" class="headerlink" title="第一个疑问是ApplicationFilterChain将所有的Filter存放在哪里？"></a>第一个疑问是ApplicationFilterChain将所有的Filter存放在哪里？</h5><p>答案是保存在ApplicationFilterChain类中的一个ApplicationFilterConfig对象的数组中。</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;**</span><br><span class="line">    * Filters.</span><br><span class="line">    *&#x2F;</span><br><span class="line">   private ApplicationFilterConfig[] filters &#x3D;  new ApplicationFilterConfig[0];</span><br></pre></td></tr></table></figure><h5 id="那ApplicationFilterConfig对象又是什么呢？"><a href="#那ApplicationFilterConfig对象又是什么呢？" class="headerlink" title="那ApplicationFilterConfig对象又是什么呢？"></a>那ApplicationFilterConfig对象又是什么呢？</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;**</span><br><span class="line"> * Implementation of a &lt;code&gt;javax.servlet.FilterConfig&lt;&#x2F;code&gt; useful in</span><br><span class="line"> * managing the filter instances instantiated when a web application</span><br><span class="line"> * is first started.</span><br><span class="line"> *</span><br><span class="line"> * @author Craig R. McClanahan</span><br><span class="line"> * @version $Id: ApplicationFilterConfig.java 1201569 2011-11-14 01:36:07Z kkolinko $</span><br><span class="line"> *&#x2F;</span><br></pre></td></tr></table></figure><p>当一个web应用首次启动时ApplicationFilterConfig会自动实例化，它会从该web应用的web.xml文件中读取配置的Filter的信息，然后装进该容器。</p><h5 id="刚刚看到在ApplicationFilterChain类中所创建的ApplicationFilterConfig数组长度为零，那它是在什么时候被重新赋值的呢？"><a href="#刚刚看到在ApplicationFilterChain类中所创建的ApplicationFilterConfig数组长度为零，那它是在什么时候被重新赋值的呢？" class="headerlink" title="刚刚看到在ApplicationFilterChain类中所创建的ApplicationFilterConfig数组长度为零，那它是在什么时候被重新赋值的呢？"></a>刚刚看到在ApplicationFilterChain类中所创建的ApplicationFilterConfig数组长度为零，那它是在什么时候被重新赋值的呢？</h5><p>是在调用ApplicationFilterChain类的addFilter()方法时。</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">   &#x2F;**</span><br><span class="line">    * The int which gives the current number of filters in the chain.</span><br><span class="line">    *&#x2F;</span><br><span class="line">   private int n &#x3D; 0;</span><br><span class="line">public static final int INCREMENT &#x3D; 10;</span><br><span class="line"></span><br><span class="line">void addFilter(ApplicationFilterConfig filterConfig) &#123;</span><br><span class="line"></span><br><span class="line">       &#x2F;&#x2F; Prevent the same filter being added multiple times</span><br><span class="line">       for(ApplicationFilterConfig filter:filters)</span><br><span class="line">           if(filter&#x3D;&#x3D;filterConfig)</span><br><span class="line">               return;</span><br><span class="line"></span><br><span class="line">       if (n &#x3D;&#x3D; filters.length) &#123;</span><br><span class="line">           ApplicationFilterConfig[] newFilters &#x3D; new ApplicationFilterConfig[n + INCREMENT];</span><br><span class="line">           System.arraycopy(filters, 0, newFilters, 0, n);</span><br><span class="line">           filters &#x3D; newFilters;</span><br><span class="line">       &#125;</span><br><span class="line">       filters[n++] &#x3D; filterConfig;</span><br><span class="line"></span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure><p>　变量n用来记录当前过滤器链里面拥有的过滤器数目，默认情况下n等于0，ApplicationFilterConfig对象数组的长度也等于0，所以当第一次调用addFilter()方法时，if (n == filters.length)的条件成立，ApplicationFilterConfig数组长度被改变。之后filters[n++] = filterConfig;将变量filterConfig放入ApplicationFilterConfig数组中并将当前过滤器链里面拥有的过滤器数目+1。</p><h5 id="那ApplicationFilterChain的addFilter-方法又是在什么地方被调用的呢？"><a href="#那ApplicationFilterChain的addFilter-方法又是在什么地方被调用的呢？" class="headerlink" title="那ApplicationFilterChain的addFilter()方法又是在什么地方被调用的呢？"></a>那ApplicationFilterChain的addFilter()方法又是在什么地方被调用的呢？</h5><p>是在ApplicationFilterFactory类的createFilterChain()方法中。</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br></pre></td><td class="code"><pre><span class="line">public ApplicationFilterChain createFilterChain(ServletRequest request, Wrapper wrapper, Servlet servlet) &#123;</span><br><span class="line"></span><br><span class="line">       &#x2F;&#x2F; get the dispatcher type</span><br><span class="line">       DispatcherType dispatcher &#x3D; null; </span><br><span class="line">       if (request.getAttribute(DISPATCHER_TYPE_ATTR) !&#x3D; null) &#123;</span><br><span class="line">           dispatcher &#x3D; (DispatcherType) request.getAttribute(DISPATCHER_TYPE_ATTR);</span><br><span class="line">       &#125;</span><br><span class="line">       String requestPath &#x3D; null;</span><br><span class="line">       Object attribute &#x3D; request.getAttribute(DISPATCHER_REQUEST_PATH_ATTR);</span><br><span class="line">       </span><br><span class="line">       if (attribute !&#x3D; null)&#123;</span><br><span class="line">           requestPath &#x3D; attribute.toString();</span><br><span class="line">       &#125;</span><br><span class="line">       </span><br><span class="line">       &#x2F;&#x2F; If there is no servlet to execute, return null</span><br><span class="line">       if (servlet &#x3D;&#x3D; null)</span><br><span class="line">           return (null);</span><br><span class="line"></span><br><span class="line">       boolean comet &#x3D; false;</span><br><span class="line">       </span><br><span class="line">       &#x2F;&#x2F; Create and initialize a filter chain object</span><br><span class="line">       ApplicationFilterChain filterChain &#x3D; null;</span><br><span class="line">       if (request instanceof Request) &#123;</span><br><span class="line">           Request req &#x3D; (Request) request;</span><br><span class="line">           comet &#x3D; req.isComet();</span><br><span class="line">           if (Globals.IS_SECURITY_ENABLED) &#123;</span><br><span class="line">               &#x2F;&#x2F; Security: Do not recycle</span><br><span class="line">               filterChain &#x3D; new ApplicationFilterChain();</span><br><span class="line">               if (comet) &#123;</span><br><span class="line">                   req.setFilterChain(filterChain);</span><br><span class="line">               &#125;</span><br><span class="line">           &#125; else &#123;</span><br><span class="line">               filterChain &#x3D; (ApplicationFilterChain) req.getFilterChain();</span><br><span class="line">               if (filterChain &#x3D;&#x3D; null) &#123;</span><br><span class="line">                   filterChain &#x3D; new ApplicationFilterChain();</span><br><span class="line">                   req.setFilterChain(filterChain);</span><br><span class="line">               &#125;</span><br><span class="line">           &#125;</span><br><span class="line">       &#125; else &#123;</span><br><span class="line">           &#x2F;&#x2F; Request dispatcher in use</span><br><span class="line">           filterChain &#x3D; new ApplicationFilterChain();</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       filterChain.setServlet(servlet);</span><br><span class="line"></span><br><span class="line">       filterChain.setSupport</span><br><span class="line">           (((StandardWrapper)wrapper).getInstanceSupport());</span><br><span class="line"></span><br><span class="line">       &#x2F;&#x2F; Acquire the filter mappings for this Context</span><br><span class="line">       StandardContext context &#x3D; (StandardContext) wrapper.getParent();</span><br><span class="line">       FilterMap filterMaps[] &#x3D; context.findFilterMaps();</span><br><span class="line"></span><br><span class="line">       &#x2F;&#x2F; If there are no filter mappings, we are done</span><br><span class="line">       if ((filterMaps &#x3D;&#x3D; null) || (filterMaps.length &#x3D;&#x3D; 0))</span><br><span class="line">           return (filterChain);</span><br><span class="line"></span><br><span class="line">       &#x2F;&#x2F; Acquire the information we will need to match filter mappings</span><br><span class="line">       String servletName &#x3D; wrapper.getName();</span><br><span class="line"></span><br><span class="line">       &#x2F;&#x2F; Add the relevant path-mapped filters to this filter chain</span><br><span class="line">       for (int i &#x3D; 0; i &lt; filterMaps.length; i++) &#123;</span><br><span class="line">           if (!matchDispatcher(filterMaps[i] ,dispatcher)) &#123;</span><br><span class="line">               continue;</span><br><span class="line">           &#125;</span><br><span class="line">           if (!matchFiltersURL(filterMaps[i], requestPath))</span><br><span class="line">               continue;</span><br><span class="line">           ApplicationFilterConfig filterConfig &#x3D; (ApplicationFilterConfig) context.findFilterConfig(filterMaps[i].getFilterName());</span><br><span class="line">           if (filterConfig &#x3D;&#x3D; null) &#123;</span><br><span class="line">               &#x2F;&#x2F; FIXME - log configuration problem</span><br><span class="line">               continue;</span><br><span class="line">           &#125;</span><br><span class="line">           boolean isCometFilter &#x3D; false;</span><br><span class="line">           if (comet) &#123;</span><br><span class="line">               try &#123;</span><br><span class="line">                   isCometFilter &#x3D; filterConfig.getFilter() instanceof CometFilter;</span><br><span class="line">               &#125; catch (Exception e) &#123;</span><br><span class="line">                   &#x2F;&#x2F; Note: The try catch is there because getFilter has a lot of </span><br><span class="line">                   &#x2F;&#x2F; declared exceptions. However, the filter is allocated much</span><br><span class="line">                   &#x2F;&#x2F; earlier</span><br><span class="line">                   Throwable t &#x3D; ExceptionUtils.unwrapInvocationTargetException(e);</span><br><span class="line">                   ExceptionUtils.handleThrowable(t);</span><br><span class="line">               &#125;</span><br><span class="line">               if (isCometFilter) &#123;</span><br><span class="line">                   filterChain.addFilter(filterConfig);</span><br><span class="line">               &#125;</span><br><span class="line">           &#125; else &#123;</span><br><span class="line">               filterChain.addFilter(filterConfig);</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       &#x2F;&#x2F; Add filters that match on servlet name second</span><br><span class="line">       for (int i &#x3D; 0; i &lt; filterMaps.length; i++) &#123;</span><br><span class="line">           if (!matchDispatcher(filterMaps[i] ,dispatcher)) &#123;</span><br><span class="line">               continue;</span><br><span class="line">           &#125;</span><br><span class="line">           if (!matchFiltersServlet(filterMaps[i], servletName))</span><br><span class="line">               continue;</span><br><span class="line">           ApplicationFilterConfig filterConfig &#x3D; (ApplicationFilterConfig) context.findFilterConfig(filterMaps[i].getFilterName());</span><br><span class="line">           if (filterConfig &#x3D;&#x3D; null) &#123;</span><br><span class="line">               &#x2F;&#x2F; FIXME - log configuration problem</span><br><span class="line">               continue;</span><br><span class="line">           &#125;</span><br><span class="line">           boolean isCometFilter &#x3D; false;</span><br><span class="line">           if (comet) &#123;</span><br><span class="line">               try &#123;</span><br><span class="line">                   isCometFilter &#x3D; filterConfig.getFilter() instanceof CometFilter;</span><br><span class="line">               &#125; catch (Exception e) &#123;</span><br><span class="line">                   &#x2F;&#x2F; Note: The try catch is there because getFilter has a lot of </span><br><span class="line">                   &#x2F;&#x2F; declared exceptions. However, the filter is allocated much</span><br><span class="line">                   &#x2F;&#x2F; earlier</span><br><span class="line">               &#125;</span><br><span class="line">               if (isCometFilter) &#123;</span><br><span class="line">                   filterChain.addFilter(filterConfig);</span><br><span class="line">               &#125;</span><br><span class="line">           &#125; else &#123;</span><br><span class="line">               filterChain.addFilter(filterConfig);</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       &#x2F;&#x2F; Return the completed filter chain</span><br><span class="line">       return (filterChain);</span><br><span class="line"></span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure><p>　　可以将如上代码分为两段，51行之前为第一段，51行之后为第二段。</p><p>　　第一段的主要目的是创建ApplicationFilterChain对象以及一些参数设置。</p><p>　　第二段的主要目的是从上下文中获取所有Filter信息，之后使用for循环遍历并调用filterChain.addFilter(filterConfig);将filterConfig放入ApplicationFilterChain对象的ApplicationFilterConfig数组中。</p><h5 id="那ApplicationFilterFactory类的createFilterChain-方法又是在什么地方被调用的呢？"><a href="#那ApplicationFilterFactory类的createFilterChain-方法又是在什么地方被调用的呢？" class="headerlink" title="那ApplicationFilterFactory类的createFilterChain()方法又是在什么地方被调用的呢？"></a>那ApplicationFilterFactory类的createFilterChain()方法又是在什么地方被调用的呢？</h5><p>是在StandardWrapperValue类的invoke()方法中被调用的。</p><img src="" alt=""><p>由于invoke()方法较长，所以将很多地方省略。</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">public final void invoke(Request request, Response response)</span><br><span class="line">       throws IOException, ServletException &#123;</span><br><span class="line">	省略中间代码..</span><br><span class="line">       ApplicationFilterFactory factory &#x3D; ApplicationFilterFactory.getInstance();</span><br><span class="line">       ApplicationFilterChain filterChain &#x3D; factory.createFilterChain(request, wrapper, servlet);</span><br><span class="line">	省略中间代码..</span><br><span class="line">       filterChain.doFilter(request.getRequest(), response.getResponse());</span><br><span class="line">	省略中间代码..</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure><p>　　那正常的流程应该是这样的：</p><p>　　在StandardWrapperValue类的invoke()方法中调用ApplicationFilterChai类的createFilterChain()方法———&gt;在ApplicationFilterChai类的createFilterChain()方法中调用ApplicationFilterChain类的addFilter()方法———&gt;在ApplicationFilterChain类的addFilter()方法中给ApplicationFilterConfig数组赋值。</p><img style="display:block;margin-left:auto;margin-right:auto" src="" alt=""><p>根据上面的代码可以看出StandardWrapperValue类的invoke()方法在执行完createFilterChain()方法后，会继续执行ApplicationFilterChain类的doFilter()方法，然后在doFilter()方法中会调用internalDoFilter()方法。</p><p>　　以下是internalDoFilter()方法的部分代码</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; Call the next filter if there is one</span><br><span class="line">if (pos &lt; n) &#123;</span><br><span class="line">	&#x2F;&#x2F;拿到下一个Filter，将指针向下移动一位</span><br><span class="line">	&#x2F;&#x2F;pos它来标识当前ApplicationFilterChain（当前过滤器链）执行到哪个过滤器</span><br><span class="line">	ApplicationFilterConfig filterConfig &#x3D; filters[pos++];</span><br><span class="line">	Filter filter &#x3D; null;</span><br><span class="line">	try &#123;</span><br><span class="line">		&#x2F;&#x2F;获取当前指向的Filter的实例</span><br><span class="line">		filter &#x3D; filterConfig.getFilter();</span><br><span class="line">		support.fireInstanceEvent(InstanceEvent.BEFORE_FILTER_EVENT, filter, request, response);</span><br><span class="line"></span><br><span class="line">		if (request.isAsyncSupported() &amp;&amp; &quot;false&quot;.equalsIgnoreCase(filterConfig.getFilterDef().getAsyncSupported())) &#123;</span><br><span class="line">		    request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE);</span><br><span class="line">		&#125;</span><br><span class="line">		if( Globals.IS_SECURITY_ENABLED ) &#123;</span><br><span class="line">		    final ServletRequest req &#x3D; request;</span><br><span class="line">		    final ServletResponse res &#x3D; response;</span><br><span class="line">		    Principal principal &#x3D; ((HttpServletRequest) req).getUserPrincipal();</span><br><span class="line">		    Object[] args &#x3D; new Object[]&#123;req, res, this&#125;;</span><br><span class="line">		    SecurityUtil.doAsPrivilege(&quot;doFilter&quot;, filter, classType, args, principal);</span><br><span class="line">		&#125; else &#123;</span><br><span class="line">		　　　　&#x2F;&#x2F;调用Filter的doFilter()方法  </span><br><span class="line">		    filter.doFilter(request, response, this);</span><br><span class="line">		&#125;</span><br></pre></td></tr></table></figure><p>　　这里的filter.doFilter(request, response, this);就是调用我们前面创建的TestFilter中的doFilter()方法。而TestFilter中的doFilter()方法会继续调用chain.doFilter(request, response);方法，而这个chain其实就是ApplicationFilterChain,所以调用过程又回到了上面调用dofilter和调用internalDoFilter方法，这样执行直到里面的过滤器全部执行。</p><p>　　如果定义两个过滤器，则Debug结果如下：</p><img style="display:block;margin-left:auto;margin-right:auto" src="" alt=""></div><div class="article-tags size-small is-uppercase mb-4"><span class="mr-2">#</span><a class="link-muted mr-2" rel="tag" href="/tags/java/">java</a><a class="link-muted mr-2" rel="tag" href="/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">设计模式</a><a class="link-muted mr-2" rel="tag" href="/tags/%E8%BD%AC%E8%BD%BD/">转载</a></div><link rel="stylesheet" href="/cdn/js/dist/css/share.min.css"><div class="social-share"></div><script src="/cdn/js/dist/js/social-share.min.js"></script><script>window.onload=function(){var o=window.document.location.href,t=window.document.location.pathname;"/memory/"===t&&(document.getElementsByClassName("navbar-logo-img")[0].src="/img/logo-pink.png",document.getElementsByClassName("footer-logo-img")[0].src="/img/logo-pink.png"),o&&$("#artTitle").html()&&(t=o.indexOf(t),o=o.substring(0,t),t=$("#artTitle").html().substring(25),$("#artTitle").html(o+"/"+t))}</script></article></div><div class="card"><div class="card-content"><h3 class="menu-label has-text-centered">喜欢这篇文章？打赏一下作者吧</h3><div class="buttons is-centered"><a class="button is-info donate"><span class="icon is-small"><i class="fab fa-alipay"></i></span><span>支付宝</span><span class="qrcode"><img src="/img/alipay.png" alt="支付宝"></span></a><a class="button is-success donate"><span class="icon is-small"><i class="fab fa-weixin"></i></span><span>微信</span><span class="qrcode"><img src="/img/wechatpay.png" alt="微信"></span></a></div></div></div><nav class="post-navigation mt-4 level is-mobile"><div class="level-start"><a class="article-nav-prev level level-item link-muted" href="/2017/12/28/history-of-browser-useragent/"><i class="level-item fas fa-chevron-left"></i><span class="level-item">浏览器野史</span></a></div><div class="level-end"><a class="article-nav-next level level-item link-muted" href="/2017/12/16/about-cnblogs-css/"><span class="level-item">关于博客园自定义样式</span><i class="level-item fas fa-chevron-right"></i></a></div></nav></div><div class="column column-right is-4-tablet is-4-desktop is-4-widescreen order-3"><div class="card widget"><div class="card-content"><nav class="level"><div class="level-item has-text-centered flex-shrink-1"><div><figure class="image is-128x128 mx-auto mb-2"><img src="/img/header.png" alt="Trainoo"></figure><p class="title is-size-4 is-block line-height-inherit">Trainoo</p><p class="is-size-6 is-block">A simple man living a simple life</p><p class="is-size-6 is-flex justify-content-center"><i class="fas fa-map-marker-alt mr-1"></i><span>Earth, Solar System</span></p></div></div></nav><nav class="level is-mobile"><div class="level-item has-text-centered is-marginless"><div><p class="heading">文章</p><a href="/archives"><p class="title">55</p></a></div></div><div class="level-item has-text-centered is-marginless"><div><p class="heading">分类</p><a href="/categories"><p class="title">12</p></a></div></div><div class="level-item has-text-centered is-marginless"><div><p class="heading">标签</p><a href="/tags"><p class="title">36</p></a></div></div></nav><div class="level"><a class="level-item button is-primary is-rounded" href="https://space.bilibili.com/19555359/bangumi" target="_blank" rel="noopener">米娜桑，一起来追番吧</a></div><div class="level is-mobile"><a class="level-item button is-transparent is-marginless" target="_blank" rel="noopener" title="Github" href="https://github.com/trainoozhou"><i class="fab fa-github"></i></a><a class="level-item button is-transparent is-marginless" target="_blank" rel="noopener" title="Facebook" href="https://facebook.com"><i class="fab fa-facebook"></i></a><a class="level-item button is-transparent is-marginless" target="_blank" rel="noopener" title="Twitter" href="https://twitter.com"><i class="fab fa-twitter"></i></a><a class="level-item button is-transparent is-marginless" target="_blank" rel="noopener" title="Dribbble" href="mailto:trainoo@163.com"><i class="fab fa-dribbble"></i></a><a class="level-item button is-transparent is-marginless" target="_blank" rel="noopener" title="RSS" href="/"><i class="fas fa-rss"></i></a></div></div></div><div class="card widget"><link href="/music/APlayer.min.css"><div id="aplayer" style="margin:0 auto"></div><script src="/music/APlayer.min.js"></script><script src="/music/APlayer_Music.js"></script></div><div class="card widget"><div class="card-content"><h3 class="menu-label">最新文章</h3><article class="media"><a class="media-left" href="/2021/04/19/bokugashinootoomotanowa/"><p class="image is-64x64"><img class="thumbnail" src="/picture/2021/20210419001.jpg" alt="仆が死のうと思ったのは — 中島美嘉"></p></a><div class="media-content size-small"><p><time datetime="2021-04-19T04:00:00.000Z">2021-04-19</time></p><p class="title is-6"><a class="link-muted" href="/2021/04/19/bokugashinootoomotanowa/">仆が死のうと思ったのは — 中島美嘉</a></p><p class="is-uppercase"><a class="link-muted" href="/categories/%E9%BB%98%E8%AE%A4/">默认</a></p></div></article><article class="media"><a class="media-left" href="/2021/04/09/ribbon-retry-problem/"><p class="image is-64x64"><img class="thumbnail" src="/picture/2021/20210409001.jpg" alt="记一次Ribbon重试配置不生效问题"></p></a><div class="media-content size-small"><p><time datetime="2021-04-09T12:30:00.000Z">2021-04-09</time></p><p class="title is-6"><a class="link-muted" href="/2021/04/09/ribbon-retry-problem/">记一次Ribbon重试配置不生效问题</a></p><p class="is-uppercase"><a class="link-muted" href="/categories/%E5%AD%A6%E4%B9%A0/">学习</a> / <a class="link-muted" href="/categories/%E5%AD%A6%E4%B9%A0/%E9%97%AE%E9%A2%98%E5%A4%84%E7%90%86/">问题处理</a></p></div></article><article class="media"><a class="media-left" href="/2021/04/07/novel-zhuixu/"><p class="image is-64x64"><img class="thumbnail" src="/picture/2021/20210407001.jpg" alt="《赘婿》摘录"></p></a><div class="media-content size-small"><p><time datetime="2021-04-06T16:00:00.000Z">2021-04-07</time></p><p class="title is-6"><a class="link-muted" href="/2021/04/07/novel-zhuixu/">《赘婿》摘录</a></p><p class="is-uppercase"><a class="link-muted" href="/categories/%E9%BB%98%E8%AE%A4/">默认</a></p></div></article><article class="media"><a class="media-left" href="/2020/05/31/blog-theme-upgrade/"><p class="image is-64x64"><img class="thumbnail" src="/picture/2020/20200531001.png" alt="记Icarus博客主题升级"></p></a><div class="media-content size-small"><p><time datetime="2020-05-31T03:30:00.000Z">2020-05-31</time></p><p class="title is-6"><a class="link-muted" href="/2020/05/31/blog-theme-upgrade/">记Icarus博客主题升级</a></p><p class="is-uppercase"><a class="link-muted" href="/categories/%E9%BB%98%E8%AE%A4/">默认</a></p></div></article><article class="media"><a class="media-left" href="/2020/03/28/jvm-monitor-practice/"><p class="image is-64x64"><img class="thumbnail" src="/picture/2020/20200328001.jpg" alt="JVM及Java监控原理与实践"></p></a><div class="media-content size-small"><p><time datetime="2020-03-28T07:33:00.000Z">2020-03-28</time></p><p class="title is-6"><a class="link-muted" href="/2020/03/28/jvm-monitor-practice/">JVM及Java监控原理与实践</a></p><p class="is-uppercase"><a class="link-muted" href="/categories/%E5%AD%A6%E4%B9%A0/">学习</a> / <a class="link-muted" href="/categories/%E5%AD%A6%E4%B9%A0/java/">java</a></p></div></article></div></div><div class="card widget"><div class="card-content"><div class="menu"><h3 class="menu-label">分类</h3><ul class="menu-list"><li><a class="level is-mobile is-marginless" href="/categories/%E5%AD%A6%E4%B9%A0/"><span class="level-start"><span class="level-item">学习</span></span><span class="level-end"><span class="level-item tag">37</span></span></a><ul class="mr-0"><li><a class="level is-mobile is-marginless" href="/categories/%E5%AD%A6%E4%B9%A0/docker/"><span class="level-start"><span class="level-item">docker</span></span><span class="level-end"><span class="level-item tag">3</span></span></a></li><li><a class="level is-mobile is-marginless" href="/categories/%E5%AD%A6%E4%B9%A0/elastic/"><span class="level-start"><span class="level-item">elastic</span></span><span class="level-end"><span class="level-item tag">1</span></span></a></li><li><a class="level is-mobile is-marginless" href="/categories/%E5%AD%A6%E4%B9%A0/java/"><span class="level-start"><span class="level-item">java</span></span><span class="level-end"><span class="level-item tag">7</span></span></a></li><li><a class="level is-mobile is-marginless" href="/categories/%E5%AD%A6%E4%B9%A0/nginx/"><span class="level-start"><span class="level-item">nginx</span></span><span class="level-end"><span class="level-item tag">1</span></span></a></li><li><a class="level is-mobile is-marginless" href="/categories/%E5%AD%A6%E4%B9%A0/python/"><span class="level-start"><span class="level-item">python</span></span><span class="level-end"><span class="level-item tag">10</span></span></a></li><li><a class="level is-mobile is-marginless" href="/categories/%E5%AD%A6%E4%B9%A0/spring/"><span class="level-start"><span class="level-item">spring</span></span><span class="level-end"><span class="level-item tag">1</span></span></a></li><li><a class="level is-mobile is-marginless" href="/categories/%E5%AD%A6%E4%B9%A0/%E7%8E%AF%E5%A2%83%E5%AE%89%E8%A3%85/"><span class="level-start"><span class="level-item">环境安装</span></span><span class="level-end"><span class="level-item tag">5</span></span></a></li><li><a class="level is-mobile is-marginless" href="/categories/%E5%AD%A6%E4%B9%A0/%E8%84%9A%E6%9C%AC%E5%91%BD%E4%BB%A4/"><span class="level-start"><span class="level-item">脚本命令</span></span><span class="level-end"><span class="level-item tag">5</span></span></a></li><li><a class="level is-mobile is-marginless" href="/categories/%E5%AD%A6%E4%B9%A0/%E9%97%AE%E9%A2%98%E5%A4%84%E7%90%86/"><span class="level-start"><span class="level-item">问题处理</span></span><span class="level-end"><span class="level-item tag">4</span></span></a></li></ul></li><li><a class="level is-mobile is-marginless" href="/categories/%E7%9B%B8%E5%86%8C/"><span class="level-start"><span class="level-item">相册</span></span><span class="level-end"><span class="level-item tag">8</span></span></a></li><li><a class="level is-mobile is-marginless" href="/categories/%E9%BB%98%E8%AE%A4/"><span class="level-start"><span class="level-item">默认</span></span><span class="level-end"><span class="level-item tag">10</span></span></a></li></ul></div></div></div><div class="card widget"><div class="card-content"><div class="menu"><h3 class="menu-label">归档</h3><ul class="menu-list"><li><a class="level is-mobile is-marginless" href="/archives/2021/04/"><span class="level-start"><span class="level-item">四月 2021</span></span><span class="level-end"><span class="level-item tag">3</span></span></a></li><li><a class="level is-mobile is-marginless" href="/archives/2020/05/"><span class="level-start"><span class="level-item">五月 2020</span></span><span class="level-end"><span class="level-item tag">1</span></span></a></li><li><a class="level is-mobile is-marginless" href="/archives/2020/03/"><span class="level-start"><span class="level-item">三月 2020</span></span><span class="level-end"><span class="level-item tag">1</span></span></a></li><li><a class="level is-mobile is-marginless" href="/archives/2019/12/"><span class="level-start"><span class="level-item">十二月 2019</span></span><span class="level-end"><span class="level-item tag">3</span></span></a></li><li><a class="level is-mobile is-marginless" href="/archives/2019/11/"><span class="level-start"><span class="level-item">十一月 2019</span></span><span class="level-end"><span class="level-item tag">1</span></span></a></li><li><a class="level is-mobile is-marginless" href="/archives/2019/10/"><span class="level-start"><span class="level-item">十月 2019</span></span><span class="level-end"><span class="level-item tag">6</span></span></a></li><li><a class="level is-mobile is-marginless" href="/archives/2019/09/"><span class="level-start"><span class="level-item">九月 2019</span></span><span class="level-end"><span class="level-item tag">2</span></span></a></li><li><a class="level is-mobile is-marginless" href="/archives/2019/07/"><span class="level-start"><span class="level-item">七月 2019</span></span><span class="level-end"><span class="level-item tag">1</span></span></a></li><li><a class="level is-mobile is-marginless" href="/archives/2019/06/"><span class="level-start"><span class="level-item">六月 2019</span></span><span class="level-end"><span class="level-item tag">2</span></span></a></li><li><a class="level is-mobile is-marginless" href="/archives/2019/05/"><span class="level-start"><span class="level-item">五月 2019</span></span><span class="level-end"><span class="level-item tag">1</span></span></a></li><a class="level is-mobile is-marginless" href="/archives/"><span class="level-start"><span class="level-item">查看全部&gt;&gt;</span></span></a></ul></div></div></div></div></div></div></section><footer class="footer"><div class="container"><div class="level"><div class="level-start"><a class="footer-logo is-block mb-2" href="/"><img class="footer-logo-img" src="/img/logo.png" alt="Trainoo的博客" height="28"></a><p class="size-small">  Powered by <a href="https://hexo.io/" target="_blank">Hexo</a> base on <a href="https://github.com/ppoffice/hexo-theme-icarus" target="_blank">Icarus</a></p></div><div class="level-mid"><div class="field has-addons"><p class="control"><a class="button is-transparent is-large" target="_blank" rel="noopener" title="Creative Commons" href="https://creativecommons.org/"><i class="fab fa-creative-commons"></i></a></p><p class="control"><a class="button is-transparent is-large" target="_blank" rel="noopener" title="Attribution 4.0 International" href="https://creativecommons.org/licenses/by/4.0/"><i class="fab fa-creative-commons-by"></i></a></p><p class="control"><a class="button is-transparent is-large" target="_blank" rel="noopener" title="Download on GitHub" href="https://github.com/ppoffice/hexo-theme-icarus"><i class="fab fa-github"></i></a></p></div></div><div class="level-end"><p class="size-small"><span><span id="statistic-times">loading...</span><script>function createTime(n){n=new Date(n);now.setTime(now.getTime()+250),days=(now-n)/1e3/60/60/24,dnum=Math.floor(days),hours=(now-n)/1e3/60/60-24*dnum,hnum=Math.floor(hours),1==String(hnum).length&&(hnum="0"+hnum),minutes=(now-n)/1e3/60-1440*dnum-60*hnum,mnum=Math.floor(minutes),1==String(mnum).length&&(mnum="0"+mnum),seconds=(now-n)/1e3-86400*dnum-3600*hnum-60*mnum,snum=Math.round(seconds),1==String(snum).length&&(snum="0"+snum),document.getElementById("statistic-times").innerHTML="♥ Security Run For <strong>"+dnum+"</strong> Days <strong>"+hnum+"</strong> Hours <strong>"+mnum+"</strong> Min <strong>"+snum+"</strong> Sec ♥"}var now=new Date;setInterval("createTime('12/14/2017 12:00:00')",250,"")</script><br></span></p><div class="size-small"><span>♥ Thanks For <strong><span id="busuanzi_value_site_uv">99+</span></strong> Visitors Come To My Site <a href="/memory" style="color:#4a4a4a">♥</a></span></div><p></p></div></div></div></footer><script src="/cdn/js/dist/jquery.min.js"></script><script src="/cdn/js/min/moment-with-locales.min.js"></script><script>moment.locale("zh-CN")</script><script>var IcarusThemeSettings={site:{url:"https://trainoo.gitee.io",external_link:{enable:!0,exclude:[]}},article:{highlight:{clipboard:!0,fold:"unfolded"}}}</script><script src="/cdn/js/dist/clipboard.min.js" defer></script><script src="/js/animation.js"></script><a id="back-to-top" title="回到顶端" href="javascript:;"><i class="fas fa-chevron-up"></i></a><script src="/js/back_to_top.js" defer></script><canvas class="fireworks" width="100%" height="100%" style="position:fixed;left:0;top:0;z-index:99999999;pointer-events:none"></canvas><script src="/js/anime.min.js" defer></script><script src="/js/fireworks.js" defer></script><script src="/cdn/js/dist/js/lightgallery.min.js" defer></script><script src="/cdn/js/dist/js/jquery.justifiedGallery.min.js" defer></script><script>window.addEventListener("load",()=>{"function"==typeof $.fn.lightGallery&&$(".article").lightGallery({selector:".gallery-item"}),"function"==typeof $.fn.justifiedGallery&&($(".justified-gallery > p > .gallery-item").length&&$(".justified-gallery > p > .gallery-item").unwrap(),$(".justified-gallery").justifiedGallery())})</script><script src="/js/main.js" defer></script><script src="/js/universe.js"></script><div class="searchbox"><div class="searchbox-container"><div class="searchbox-header"><div class="searchbox-input-container"><input class="searchbox-input" type="text" placeholder="想要查找什么..."></div><a class="searchbox-close" href="javascript:;">×</a></div><div class="searchbox-body"></div></div></div><script src="/js/insight.js" defer></script><script>document.addEventListener("DOMContentLoaded",function(){loadInsight({contentUrl:"/content.json"},{hint:"想要查找什么...",untitled:"(无标题)",posts:"文章",pages:"页面",categories:"分类",tags:"标签"})})</script></body></html>